package main

/*
* 获取Docker官方仓库crt证书
* 建议使用Golang 1.13.0及以上版本
* By gas
 */

import (
	"bufio"
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"log"
	"os"
)

const (
	HOST = "index.docker.io"
	PORT = 443
)

func main() {
	var crtPath string = fmt.Sprintf("./%s.crt", HOST)
	_, _ = os.Create(crtPath)
	f, _ := os.OpenFile(crtPath, os.O_WRONLY|os.O_APPEND, 0644)
	defer func(f *os.File) {
		_ = f.Close()
	}(f)

	// 保存证书
	var cPem string
	cer := getConnect()
	write := bufio.NewWriter(f)
	for _, c := range cer {
		cPem = toPEFormat(c)
		_, _ = write.WriteString(cPem)
	}
	_ = write.Flush()
}

// 创建连接
func getConnect() []*x509.Certificate {
	c := &tls.Config{InsecureSkipVerify: true}
	con, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", HOST, PORT), c)
	if err != nil {
		log.Fatal(err)
	}
	defer func(con *tls.Conn) {
		err = con.Close()
		if err != nil {
		}
	}(con)
	return con.ConnectionState().PeerCertificates
}

// 保存PEM格式
func toPEFormat(crt *x509.Certificate) string {
	b := pem.Block{Type: "CERTIFICATE", Bytes: crt.Raw}
	return string(pem.EncodeToMemory(&b))
}
